// 封装axios
import axios from 'axios'
import store from '@/store'
import { Toast } from 'antd-mobile'
import { customHistory } from './history'
// import { logout } from '@/store/actions'

const http = axios.create({
  baseURL: 'http://toutiao.itheima.net/v1_0',
  timeout: 5000,
})

// 请求拦截器
http.interceptors.request.use((config) => {
  const {
    login: { token },
  } = store.getState()
  // 除了登录请求外, 其他请求统一添加token
  if (!config.url?.startsWith('/authorizations')) {
    config.headers!.Authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截求
http.interceptors.response.use(undefined, (error) => {
  // 响应失败时，执行此处的回调函数
  if (!error.response) {
    Toast.show({
      content: '网络繁忙, 请稍后再试',
      duration: 1000,
    })
    return Promise.reject(error)
  }
  if (error.response.status === 401) {
    Toast.show({
      content: '登录超时, 请重新登录',
      duration: 1000,
      // 在路由外部环境，使用customHistory
      afterClose: () => {
        customHistory.push('/login', {
          from: customHistory.location.pathname,
        })
      },
    })
    return Promise.reject(error)
  }
})
export { http }
